package tgc.edu.fhh.web.controller;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import tgc.edu.fhh.custom.AjaxResult;
import tgc.edu.fhh.custom.TablePageable;
import tgc.edu.fhh.entity.Course;
import tgc.edu.fhh.entity.Grade;
import tgc.edu.fhh.entity.Student;
import tgc.edu.fhh.sercurity.UserUtils;
import tgc.edu.fhh.service.CourseService;
import tgc.edu.fhh.service.GradeService;
import tgc.edu.fhh.service.StudentService;
import tgc.edu.fhh.web.form.GradeForm;


@RestController
@RequestMapping(value = "/grade")
public class GradeController {
	@Autowired
	private GradeService service;
	@Autowired
	private CourseService courseservice;
	@Autowired
	private StudentService studentService;
	@Autowired
	private UserUtils userUtils;
	@RequestMapping(value = "/page")
	public Object page(TablePageable page,GradeForm form) {
		if(form.getCourseId()!=null) {
			List<Student> student = studentService.findBytbclassId(form.getTbClassId());
			List<Student> grades=service.findStudentByCourseId(form.getCourseId());
			 if(grades.isEmpty()) {
				 for(Student student2:student) {
					 Course course2 = courseservice.findById(form.getCourseId());
					 Grade grade=new Grade(0,student2,course2);
					 service.save(grade);
				 }
			}else {
				List temp=new ArrayList(student);
				temp.retainAll(grades);
				student.removeAll(temp);
				List<Student> list=new ArrayList<Student>();
				list.addAll(student);
				for (Student student2 : list) {
					 Course course2 = courseservice.findById(form.getCourseId());
					 Grade grade=new Grade(0,student2,course2);
					 service.save(grade);
				}
			}
		}
		PageRequest pagerequest = page.buildPageRequest();
		Specification<Grade> spec = buildSpec(form);
		Page<Grade> page2 = service.findAll(spec,pagerequest);
		return new AjaxResult(AjaxResult.buildTableResult(page2));
	}
	
	@RequestMapping(value = "/upNow")
	public Object upNow(ModelMap modelmap,GradeForm form) {
		try {
			String gr = form.getGrade();
			Grade grade = service.findById(form.getId());
			grade.setGrade(gr);
			service.save(grade);
			return new AjaxResult("数据保存成功");
		}catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}
	@RequestMapping(value = "/classGradeList")
	public Object classGradeList(Integer bjId) {
		HashMap<String, Object> result=new HashMap<String, Object>();
		if(bjId==null) {
			Student stu=(Student) userUtils.getUser();
			bjId=stu.getTbclass().getId();
		}
		List<Course> courses=service.findCoursesByClassId(bjId);
		List<String> columnNames=new ArrayList<String>();
		columnNames.add("学号");
		columnNames.add("姓名");
		for (Course course : courses) {
			columnNames.add(course.getCourseName());
		}
		columnNames.add("总分");
		result.put("colNames", columnNames);
		List<HashMap<String, Object>> rows=new ArrayList<HashMap<String,Object>>();
		List<Object[]> tableData=service.getTableDataByCoursesAndTbClassId(courses,bjId);
		//System.out.println(tableData);
		for(int i=0;i<tableData.size();i++) {
			Object[] objs = tableData.get(i);
			HashMap<String, Object> row=new HashMap<String, Object>();
			for(int j=0;j<objs.length;j++) {
				row.put(columnNames.get(j), objs[j]);
			}
			rows.add(row);
		}
		result.put("tableData",rows);		
		
		return new AjaxResult("数据提取成功", result);
	}

	private Specification<Grade> buildSpec(GradeForm form) {
		@SuppressWarnings("serial")
		Specification<Grade> spec = new Specification<Grade>() {

			@Override
			public Predicate toPredicate(Root<Grade> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String search = form.getSearch();
				if (StringUtils.hasText(search)) {
					HashSet<Predicate> rules2 = new HashSet<>();
					rules2.add(cb.like(root.get("grade"),"%"+search+"%" ));
					rules2.add(cb.like(root.get("student").get("stuNo"),"%"+search+"%" ));
					rules2.add(cb.like(root.get("student").get("name"),"%"+search+"%" ));
					rules2.add(cb.like(root.get("student").get("sex"),"%"+search+"%" ));
					rules2.add(cb.like(root.get("course").get("courseName"),"%"+search+"%" ));
					rules.add(cb.or(rules2.toArray(new Predicate[rules2.size()])));
				}
				Integer tbclassId = form.getTbClassId();
				if (tbclassId!=null) {
					rules.add(cb.like(root.get("student").get("tbclass").get("id").as(String.class), "%"+tbclassId+"%"));
				}
				Integer couId = form.getCourseId();
				if (couId!=null) {
					rules.add(cb.like(root.get("course").get("id").as(String.class), "%"+couId+"%"));
				}
				Integer stuId = form.getStudentId();
				if (stuId!=null) {
					rules.add(cb.like(root.get("student").get("id").as(String.class), "%"+stuId+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
			
		};
		return spec;
	}

}
